package hs

import (
	"context"
	"fmt"
	"log"
	"net"
	"net/http"

	"gitee.com/go-errors/errors"
	"gitee.com/go-wena/env"
)

func Start(ctx context.Context, handler http.Handler, options ...Option) {
	srv := &http.Server{
		Handler: handler,
		BaseContext: func(l net.Listener) context.Context {
			log.Printf("[http] 已启动: %s\n", l.Addr().String())
			return context.Background()
		},
	}

	for _, option := range options {
		option.Apply(srv)
	}

	if srv.Addr == "" {
		var (
			host     = "0.0.0.0"
			port     = env.GetInt("http.port")
			internal = env.GetBool("http.internal")
		)
		if internal {
			host = "127.0.0.1"
		}
		if port == 0 {
			port = 2345
		}
		srv.Addr = fmt.Sprintf("%s:%d", host, port)
	}

	var lc net.ListenConfig
	ln, err := lc.Listen(ctx, "tcp", srv.Addr)

	if err != nil {
		log.Printf("[http] %v\n", err)
		return
	}

	go func() {
		<-ctx.Done()
		log.Printf("[http] 停止")
		_ = srv.Shutdown(context.Background())
	}()

	log.Printf("[http] 启动: %s\n", srv.Addr)
	if err := srv.Serve(ln); err != nil {
		if errors.Is(err, http.ErrServerClosed) {
			log.Printf("[http] 已停止\n")
		} else {
			log.Printf("[http] 已停止: %v\n", err)
		}
	} else {
		log.Printf("[http] 已停止\n")
	}
}
